package com.jx.daoimpl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.jx.dao.FindAllDepDao;
import com.jx.dao.FindFuncByDidDao;
import com.jx.model.Dep;
import com.jx.util.JDBCUtil;

public class FindAllDepDaoImpl implements FindAllDepDao{
	/**
	 * 查询所有部门
	 */
	@Override
	public List<Dep> findAllDeoDao(int start,int pagesize) {
		// TODO Auto-generated method stub
		List<Dep> deps=new ArrayList<Dep>();
		Connection con=JDBCUtil.getConnection();
		
		StringBuffer sql=new StringBuffer("select * from j_dep limit ?,?");
		//根据部门功能的id查询出部门的功能名字
		StringBuffer sql2=new StringBuffer("SELECT j_func.fname FROM dep_func,j_func WHERE j_func.fid=dep_func.fid and did=?");
		try {
			PreparedStatement pst=con.prepareStatement(sql.toString());
			pst.setInt(1, start);
			pst.setInt(2, pagesize);
			ResultSet res=pst.executeQuery();
			while(res.next()){
					String funcs="";
					PreparedStatement pst2=con.prepareStatement(sql2.toString());
					pst2.setInt(1, res.getInt("did"));
					ResultSet res2=pst2.executeQuery();
					while(res2.next()){
						funcs+=res2.getString("fname")+",";
					}
					Dep dep=new Dep(res.getInt("did"),res.getString("dname"),res.getString("ddes"),funcs);
					deps.add(dep);				
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return deps;
	}
	/**
	 * 查询所有部门的总数
	 */
	@Override
	public int findTotalDep() {
		// TODO Auto-generated method stub
		int total=0;
		Connection con=JDBCUtil.getConnection();
		StringBuffer sql=new StringBuffer("select count(did) dtotal from j_dep ");
		try {
			PreparedStatement pst=con.prepareStatement(sql.toString());
			ResultSet res=pst.executeQuery();
			while(res.next()){
				total=res.getInt("dtotal");
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return total;
	}

}
